package ml.classification.filter;

import java.util.ArrayList;

public class MajorityVotingFilter extends PostProcessingFilter {

	public MajorityVotingFilter(final int n, final int iterations,
			final boolean isSpeech) {
		super();
		this.n = n;
		this.iterations = iterations;
		this.isSpeech = isSpeech;
	}

	@Override
	public ArrayList<Integer> apply(final ArrayList<Integer> list) {
		final ArrayList<Integer> newList = new ArrayList<>();
		ArrayList<Integer> currentList = list;
		int votedTrue;
		int votedFalse;

		for (int i = 0; i < iterations; i++) {
			for (int j = 0; j < currentList.size(); j++) {
				votedTrue = 0;
				votedFalse = 0;
				for (int k = j - n; k <= j + n; k++) {
					if (k >= 0 && k < currentList.size()) {
						if (currentList.get(k) == 1) {
							votedTrue++;
						} else {
							votedFalse++;
						}
					}
				}
				if (isSpeech) {
					if (votedTrue > votedFalse) {
						newList.add(j, 1);
					} else {
						newList.add(j, 0);
					}
				} else {
					if (votedTrue > votedFalse) {
						newList.add(j, 1);
					} else {
						newList.add(j, 0);
					}
				}

			}
			currentList = new ArrayList<>();
			for (final Integer x : newList) {
				currentList.add(x);
			}
		}
		return currentList;
	}

	@Override
	public String getFilterName() {
		return "MajorityVotingFilter";
	}

}
